<?php
/**
 * Действия для модуля "post"
 *
 * @package    Forum Lite
 * @subpackage post
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class postActions extends sfActions
{
	/**
	 * Индекс - обработчик, Показывает главную страницу проекта 
	 * 
	 * @param sfWebRequest $request
	 */
	public function executeIndex(sfWebRequest $request)
	{
		$this->pager = new sfDoctrinePager('post', sfConfig::get('app_max_posts_on_homepage'));
		$this->pager->setTableMethod("mainPage");
		$this->pager->setPage($request->getParameter('page', 1));
		$this->pager->init();
		
		$statistic = Doctrine::getTable('stat')->getStatistic();
		$this->users = $statistic->getUsers();
		$this->comments = $statistic->getComments();
		$this->commentsToday = $statistic->getCommentsToday();
		$this->commentsYesterday = $statistic->getCommentsYesterday();
	}
	
	/**
	 * Показывает страницу выбранного поста
	 * 
	 * @param sfWebRequest $request
	 */
	public function executeShow(sfWebRequest $request)
	{
		// Get selected topic object
		$this->post = Doctrine::getTable('post')->getTopic($request->getParameter('id'));
		
		// Get comment list
		$this->comments = Doctrine::getTable('comment')->getCommentListByTopicId($this->post->getId());
		
		$this->form = new commentForm(new Comment());
		$this->form->getObject()->setPostId($this->post->getId());
		$this->form->getObject()->setUserId($this->getUser()->getUserId());
		
		if($request->isMethod(sfRequest::POST))
		{
			$this->form->bind($request->getParameter($this->form->getName()), $request->getFiles($this->form->getName()));
			if($this->form->isValid())
			{
				$comment = $this->form->save();
				$this->form->getObject()->multiplyCommentsCount();
				$this->redirect('@showpost?module=post&action=show&id=' . $comment->getPostId());
			}
		}
		$this->forward404Unless($this->post);
	}
	/**
	 * Показывает форму добавления нового поста
	 * 
	 * @param sfWebRequest $request
	 */
	public function executeNew(sfWebRequest $request)
	{
		$this->form = new postForm();
	}
	/**
	 * Обрабатывает пост запрос от формы добавления нового поста 
	 * 
	 * @param sfWebRequest $request
	 */
	public function executeCreate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST));
		$this->form = new postForm();
		$this->form->getObject()->setUserId($this->getUser()->getUserId());
		$this->processForm($request, $this->form);
		$this->setTemplate('new');
	}
	/**
	 * Обрабатывает форму
	 * 
	 * @param sfWebRequest $request
	 * @param sfForm $form
	 */
	protected function processForm(sfWebRequest $request, sfForm $form)
	{
		$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
		
		if($form->isValid())
		{
			$post = $form->save();
			$this->redirect('@homepage?module=post&action=index');
		}
	}
}
